<template>
  <base-breadcrumb>
    <a-row :gutter="10"  class="page-height">
      <!-- 树搜索 -->
      <a-col :span="6">
        <a-card  class="page-height-tree">
          <title-name title="公司组织架构" />
          <!-- 公司组织树搜索 -->
          <tree-organization
            ref="treeOrganization"
            :expand-by-auto="true"
            :selected-keys.sync="selectedKeys"
            :select-options.sync="selectOptions"
            :contain-virtual="$route.meta.isCompany"
            :org-query="orgQuery"
            :show-child-with-search="true"
            :filter-fn="handleFilterTree"
            @loader="getTable"
            @onOrgSelect="orgSelect"
            :isFilterNode.sync="isFilterNode"
            :isFilterIcon.sync="isFilterIcon"
            @updateIsFilterNode="updateIsFilterNode"
            :isBranchOpen="true"
            :initExpandAll="true"
          />
        </a-card>
      </a-col>
      <a-col :span="18" class="page-height-list-wrapper">
        <searchData
          :search-data="searchArr"
          @search="handleSearch"
        />
        <a-card class="mb20 page-height-list">
          <list-table
            ref="table"
            row-key="id"
            :columns="[
              { title: '序号', width: 70, customRender: (text, record, index) => index + 1 },
              { title: '组织名称', dataIndex: 'name', key: 'name' },
              { title: '组织编码', dataIndex: 'code', key: 'code' },
              { title: '上级组织', dataIndex: 'pName', key: 'pName' },
              { title: '组织类型', dataIndex: 'type', key: 'type', customRender: val => typeList.find(item => item.id == val).name },
              { title: '部门分管领导', dataIndex: 'leaderPostName', key: 'leaderPostName' },
              { title: '状态', dataIndex: 'enable', key: 'enable', customRender: val => val == 1 ? '可用' : '不可用' },
              { title: '操作', scopedSlots: { customRender: 'operation' } },
            ]"
            :request="loadData"
            :alert="true"
          >
          <div
            slot="prefix"
            v-if="!$route.meta.isCompany"
            class="pub-table-action-btn"
          >
            <a-button
              v-if="!!selectedKeys[0]"
              v-btnPermission="'sy_002_add_02'"
              icon="plus"
              class="btn_right"
              type="primary"
              @click="handleUpdate('add')"
            >
              新增下级组织机构
            </a-button>
            <a-button
              v-if="!!selectedKeys[0]"
              v-btnPermission="'sy_002_edn_03'"
              class="btn_right"
              icon="edit"
              type="primary"
              @click="handleEditCurrent"
            >
              编辑当前所选组织
            </a-button>
          </div>
          <template
              slot="leaderPostName"
              slot-scope="text"
            >
              {{ text || '无' }}
            </template>
            <template
              slot="operation"
              slot-scope="text, record"
            >
              <MoreButton>
                <a
                  v-btnPermission="'sy_002_loo_01'"
                  @click="handleUpdate('look', record)"
                >查看</a>
                <a
                  v-if="!$route.meta.isCompany"
                  v-btnPermission="'sy_002_edi_04'"
                  @click="handleUpdate('edit', record)"
                >编辑</a>
                <!-- <a
                  v-if="!$route.meta.isCompany"
                  v-btnPermission="'sy_002_del_05'"
                  @click="handleUpdate('delete', record)"
                >删除</a> -->
              </MoreButton>
            </template>
          </list-table>
        </a-card>
      </a-col>
    </a-row>
    <UpdateOrgModal :visible.sync="modalVisible" type="company" :transmit="addOrEditData" @change="onUpdateModalChange" />
  </base-breadcrumb>
</template>

<script>
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { searchArr } from './model'
import { typeList } from './companyModal/postManageModal/model'
import { getOrgManageList, deleteOrgList } from '@/api/system/system'
import UpdateOrgModal from './companyModal/UpdateOrgModal'

export default {
  name: 'CompanyOrgManage',
  components: {
    TreeOrganization,
    UpdateOrgModal
  },
  data() {
    return {
      isFilterIcon: true, //控制图标是否隐藏
      isFilterNode: false, //树节点是否隐藏节点
      //密码重置
      psw: {
        visible: false,
      },
      bindOrg: {
        visible: false,
      },
      updateStatus: {
        visible: false,
      },
      searchArr: searchArr,
      chooseData: 0,
      typeList,
      tableData: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      selectedOrg: {},

      orgId: '',

      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
          this.getTable() //显示列表的接口名称
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getTable()
        },
      },
      pathName: this.$route.path,

      isTableList: false,
      queryParam: {},  // 搜索参数
      loadData: (parameter) => {
        if (!this.isTableList) return false;
        let searchData = {
          ...this.queryParam,
          pid: this.selectedKeys[0],
          // containVirtual: false,
          resultWithLeaderName: true, // 查询部门分管领导
          baseOrgType: 0,
          types: '1,2,3,7,8',
          cascade: !!this.selectedKeys[0]
        }
        if (!this.isFilterNode) {
          searchData.enable = 1
        } else {
          delete searchData.enable
        }
        const requestParameters = Object.assign({pageNum: parameter.pageNo, pageSize: parameter.pageSize,}, searchData)

        return getOrgManageList(requestParameters).then((res) => {
          res.code = res.status;
          res.totalSize = res.data.total;
          res.data = res.data.list;
          return res
        })
      }, // 加载数据方法 必须为 Promise 对象
      modalVisible: false,
      addOrEditData: {}
    }
  },
  computed: {
    orgQuery() {
      return {
        baseOrgType: 0,
        containVirtual: 1,
        // containTags: ["CO", "EXTEND"],
        types: '1,2,3,7,8'
      }
        // 公司架构和基本架构的查询参数不同
      // return this.$route.meta.isCompany
      //   ? {
      //       containTags: ['CO', 'EXTEND'],
      //     }
      //   : {
      //       notContainTags: ['EXTEND'],
      //     }
    },
  },
  watch: {
    modalVisible:{
      handler(val){
        if(!val){
          this.addOrEditData = {}
        }
      }
    }
  },
  mounted() {
    this.$refs.treeOrganization.getList().then((res) => {
      this.getTable()
    })
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      this.getTable()
    })
  },
  beforeDestroy() {
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    updateIsFilterNode() {
      this.isFilterNode = !this.isFilterNode;
      this.handleSearch(this.queryParam)
    },
    handleFilterTree(item) {
      if(item.data.enable == 0){
        return this.isFilterNode
      }else {
        return true
      }
    },
    handleUpdate(type, data = {}) {
      if(type === 'delete'){
      }else{
        data = type === 'add' ? { id: this.selectedKeys[0], parentId: this.selectedOrg.id} : data
        this.addOrEditData = {
          ...data,
          pageType: type,
        }
        this.modalVisible = true
      }
      // const commonHandler = () => {
      //   this.$router.push({
      //     path: '/system/organizationManage/updateOrg',
      //     query: {
      //       isCompany: this.$route.meta.isCompany,
      //       pageType: type,
      //       id: data.id || '',
      //       parentId: data.parentId || data.pid || this.selectOptions.id, // 当新增下级时，需要使用选中的节点作为父级组织
      //     },
      //   })
      // }
      // const typeMap = {
      //   add: commonHandler,
      //   edit: commonHandler,
      //   look: commonHandler,
      //   delete: () => {
      //     this.handleDeleteWarning(data)
      //   },
      // }
      // typeMap[type] && typeMap[type]()
    },
    /**
     *@desc  获取组织列表
     *@param {}
     */
    getTable() {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        // this.pagination.defaultCurrent=1
        // 获取列表
        // setTimeout(that.handleSearch)
        this.selectedOrg = {
          id: this.selectedKeys[0]
        }
        this.isTableList = true;
        this.$refs.table.refresh(true)
      }
    },
    orgSelect(org) {
      this.selectedOrg = org
      this.pagination.defaultCurrent = 1
      if (!org) {
        this.selectedKeys[0] = ''
        this.handleSearch(this.queryParam)
      }
    },
    /**
     *@desc  table表格搜索
     *@param {}
     */
    handleSearch(value) {
      // this.handleTable(value)
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     *@desc  table表格列表
     *@param {}
     */
    handleTable(params) {
      let _this = this
      let searchData = {
        ...params,
        pid: _this.selectedKeys[0],
        pageNum: _this.pagination.defaultCurrent,
        pageSize: _this.pagination.defaultPageSize,
        containVirtual: false,
        resultWithLeaderName: true, // 查询部门分管领导
      }
      getOrgManageList(searchData).then((res) => {
        if (res.status === 200) {
          _this.pagination.total = res.data.total
          _this.tableData = res.data.list
        }
      })
    },
    /**
     *@desc  table表格选中
     *@param {}
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      let _this = this
      _this.selectId = []
      selectedRows.map((item) => {
        // 选中id
        _this.selectId.push(item.id)
      })
      this.chooseData = this.chooseData + selectedRows.length
      _this.selectedRowKeys = selectedRowKeys
      _this.selectedRows = selectedRows
    },
    handleEditCurrent() {
      const record = this.selectOptions.data || this.selectOptions
      this.handleUpdate('edit', record)
    },
    onUpdateModalChange(){
      // this.$refs.table.refresh(true)
      this.$refs.treeOrganization.getList().then((res) => {
        this.getTable()
      })
    },
    /**
     *@desc  table列表删除
     *@param {}
     */
    handleDeleteWarning(record) {
      let _this = this
      _this.$confirm({
        title: `你确定要删除${record.name}吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.handleDelete(record)
        },
        onCancel() {
          
        },
      })
    },

    handleDelete(record) {
      let _this = this
      let params = {
        id: record.id,
      }
      deleteOrgList(params)
        .then((res) => {
          if (res.status === 200) {
            //删除成功
            _this.$refs.treeOrganization.getList().then((res) => {
              _this.getTable()
            })
          }
        })
        .catch((err) => {
          console.log('失败', err)
          //删除失败
        })
    },
  },
}
</script>
